﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using EHR.Common;
using CommunitySystem.Common;

namespace CommunitySystem.PageView.AdvancedCustomerQuery
{
    public partial class CustomerizeQueryWindow : ChildWindow
    {
        private CustomerQuery.CustomerQueryClient client = null;
        public CustomerizeQueryWindow(int id)
        {
            InitializeComponent();
            client = new CustomerQuery.CustomerQueryClient();
            client.GetQuery_CustomerQueryCompleted += new EventHandler<CustomerQuery.GetQuery_CustomerQueryCompletedEventArgs>(client_GetQuery_CustomerQueryCompleted);
            client.GetQuery_ColumnCollectionCompleted += new EventHandler<CustomerQuery.GetQuery_ColumnCollectionCompletedEventArgs>(client_GetQuery_ColumnCollectionCompleted);
            client.GetQuery_ColumnCollectionAsync("1=1");
            client.SaveQuery_CustomerQueryCompleted += new EventHandler<CustomerQuery.SaveQuery_CustomerQueryCompletedEventArgs>(client_SaveQuery_CustomerQueryCompleted);
            if (Session.LoginUser.LoginName.ToLower() != "admin")
            {
                rbNo.IsEnabled = false;
                rbYes.IsEnabled = false;
            }
            if (id > 0)
                client.GetQuery_CustomerQueryAsync("ID=" + id);
            else
            {
                entity = new CustomerQuery.Query_CustomerQuery()
                {
                    LoginUser = Session.LoginUser.LoginName,
                    RowSelection = new System.Collections.ObjectModel.ObservableCollection<CustomerQuery.Query_ColumnsSelection>(),
                    IsTemplete = false,
                    ColumnSelection = new System.Collections.ObjectModel.ObservableCollection<CustomerQuery.Query_ColumnsSelection>(),
                    ShowColumn = new System.Collections.ObjectModel.ObservableCollection<CustomerQuery.Query_ShowColumn>(),
                    ShowType = true
                };
                this.DataContext = entity;
                    
            }
        }

        void client_SaveQuery_CustomerQueryCompleted(object sender, CustomerQuery.SaveQuery_CustomerQueryCompletedEventArgs e)
        {
            if (e.Result == true)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功!");
                this.DialogResult = true;
            }
            else
            {
                if (e.Error != null && !string.IsNullOrEmpty(e.Error.Message))
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("保存失败:\n" + e.Error.Message);
                else
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("保存失败");
                }
            }
        }

        private System.Collections.ObjectModel.ObservableCollection<CommunitySystem.CustomerQuery.Query_ColumnCollection> AllColumnsCollection = null;
        void client_GetQuery_ColumnCollectionCompleted(object sender, CustomerQuery.GetQuery_ColumnCollectionCompletedEventArgs e)
        {
            AllColumnsCollection = e.Result;
            //if (_entity.RowSelection != null)
            //{
            //    foreach (var r in _entity.RowSelection)
            //    {
            //        var a = AllColumnsCollection.Where(c => c.ID == r.ColumnID).FirstOrDefault();
            //        if (a != null)
            //            AllColumnsCollection.Remove(a);
            //    }
            //}
            //if (_entity.ColumnSelection != null)
            //{
            //    foreach (var r in _entity.RowSelection)
            //    {
            //        var a = AllColumnsCollection.Where(c => c.ID == r.ColumnID).FirstOrDefault();
            //        if (a != null) 
            //            AllColumnsCollection.Remove(a);
            //    }
            //}
        }

        private CustomerQuery.Query_CustomerQuery _entity = null;
        private CustomerQuery.Query_CustomerQuery entity
        {
            set
            {
                if (value != _entity)
                {
                    _entity = value;
                    this.DataContext = _entity;
                    rowSelection.ItemsSource = _entity.RowSelection;
                    columnSelection.ItemsSource = _entity.ColumnSelection;
                    if (_entity.IsTemplete == true)
                    {
                        rbYes.IsChecked = true;
                    }
                    else
                    {
                        rbNo.IsChecked = true;
                    }
                }
            }
            get { return _entity; }
        }
        void client_GetQuery_CustomerQueryCompleted(object sender, CustomerQuery.GetQuery_CustomerQueryCompletedEventArgs e)
        {
            entity = e.Result.FirstOrDefault();
            this.DataContext = entity;
            dtbQueryType.Field = "QueryType";
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (tcTab.SelectedIndex < tcTab.Items.Count - 1)
            {
                tcTab.SelectedIndex++;
            }
            else
            {
                if (string.IsNullOrEmpty(entity.Name))
                {
                    SilverlightMessageBoxLibrary.Message.InfoMessage("名称不能为空!");
                    return;
                    
                }
                if (entity.RowSelection.Count <= 0)
                {
                    SilverlightMessageBoxLibrary.Message.InfoMessage("行纬度不能为空!");
                    return;
                }
                if (entity.ColumnSelection.Count <= 0)
                {
                    SilverlightMessageBoxLibrary.Message.InfoMessage("列纬度不能为空!");
                    return;
                }
                if (entity.ID > 0 && entity.IsTemplete == true && entity.LoginUser != Session.LoginUser.LoginName)
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("您不是该模版的创建者,您没有该模版的编辑权限");
                    return;
                }
                //保存操作
                client.SaveQuery_CustomerQueryAsync(entity);
            }
            
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void ChildWindow_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                OKButton_Click(null, null);
            }
        }

        private void tcTab_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
        	// 在此处添加事件处理程序实现。
            if (tcTab != null && tcTab.SelectedIndex == tcTab.Items.Count - 1)
            {
                OKButton.Content = "保存";
            }
            else if(OKButton != null)
            {
                OKButton.Content = "下一步";
            }
                
        }

		/// <summary>
		/// 新增行纬度
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void ImageButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// 在此处添加事件处理程序实现。
            RowSelectWindow window = new RowSelectWindow(AllColumnsCollection, new CustomerQuery.Query_ColumnsSelection() { CustomerQueryID = _entity.ID }, _entity);
            window.Show();
            window.Closed -= new EventHandler(window_Closed);
            window.Closed += new EventHandler(window_Closed);
        }

        void window_Closed(object sender, EventArgs e)
        {
            RowSelectWindow window = sender as RowSelectWindow;
            if (window != null && window.DialogResult == true)
            {
                entity.RowSelection.Add(window.result);
            }
            else
            {
                ColSelectWindow cw = sender as ColSelectWindow;
                if (cw != null && cw.DialogResult == true)
                {
                    entity.ColumnSelection.Add(cw.result);
                }
            }
        }

		/// <summary>
		/// 新增列纬度
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void ImageButton2_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // 在此处添加事件处理程序实现。
            ColSelectWindow window = new ColSelectWindow(AllColumnsCollection, new CustomerQuery.Query_ColumnsSelection() { CustomerQueryID = _entity.ID }, _entity);
            window.Show();
            window.Closed -= new EventHandler(window_Closed);
            window.Closed+=new EventHandler(window_Closed);
        }
        private CustomerQuery.Query_ColumnsSelection SelectRowOrCol = null;
        //"字符型", "数字型", "日期型" 
        private void rowSelection_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            // 在此处添加事件处理程序实现。
            var item = rowSelection.SelectedItem as CustomerQuery.Query_ColumnsSelection;
            if (item != null)
            {
                SelectRowOrCol = item;
                imgAddRow.Visibility = Visibility.Visible;

                DataTemplate dt = null;
                lbRowValues.ItemTemplate = null;
                var temp = LayoutRoot.Resources;
                _CurrentType = item.ColumnType;
                switch (item.ColumnType)
                {
                    case "字符型":
                        dt = temp["tempString"] as DataTemplate;
                        
                        break;
                    case "数字型":
                        dt = temp["tempInt"] as DataTemplate;
                        break;
                    case "日期型":
                        dt = temp["tempDate"] as DataTemplate;
                        break;
                }
                lbRowValues.ItemTemplate = dt;
            }
        }
        private string _CurrentType = string.Empty;
        private void columnSelection_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            // 在此处添加事件处理程序实现。
            var item = columnSelection.SelectedItem as CustomerQuery.Query_ColumnsSelection;
            if (item != null)
            {
                SelectRowOrCol = item;
                imgAddCol.Visibility = Visibility.Visible;

                DataTemplate dt = null;
                lbColValues.ItemTemplate = null;
                var temp = LayoutRoot.Resources;
                _CurrentType = item.ColumnType;
                switch (item.ColumnType)
                {
                    case "字符型":
                        dt = temp["tempString"] as DataTemplate;
                        break;
                    case "数字型":
                        dt = temp["tempInt"] as DataTemplate;
                        break;
                    case "日期型":
                        dt = temp["tempDate"] as DataTemplate;
                        break;
                }
                lbColValues.ItemTemplate = dt;
            }
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var item = ((sender as Image).Parent as StackPanel).DataContext as CustomerQuery.Query_ColumnsSelection;
            if (item != null && item.ColumnOrRow == "row")
            {
                _entity.RowSelection.Remove(item);
            }
            if (item != null && item.ColumnOrRow == "column")
            {
                _entity.ColumnSelection.Remove(item);
            }
        }

        private void rbNo_Click(object sender, RoutedEventArgs e)
        {
            if (rbNo.IsChecked == true)
            {
                _entity.IsTemplete = false;
            }
            if (rbYes.IsChecked == true)
                _entity.IsTemplete = true;
        }

        private void imgString_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var item = ((sender as Image).Parent as StackPanel).DataContext as CustomerQuery.Query_ColumnValue;
            if (item != null)
                SelectRowOrCol.values.Remove(item);

        }

        private void imgInt_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var item = ((sender as Image).Parent as StackPanel).DataContext as CustomerQuery.Query_ColumnValue;
            if (item != null)
                SelectRowOrCol.values.Remove(item);
      
        }

        private void imgDate_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var item = ((sender as Image).Parent as StackPanel).DataContext as CustomerQuery.Query_ColumnValue;
            if (item != null)
                SelectRowOrCol.values.Remove(item);
           
        }

        private void imgAddRow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var item = new CustomerQuery.Query_ColumnValue();
           
            if (item != null)
                SelectRowOrCol.values.Add(item);
        }

        private void cbCompetorIint_Loaded(object sender, RoutedEventArgs e)
        {
            ComboBox cb = sender as ComboBox;

            var sign = (cb.Tag as CustomerQuery.Query_ColumnValue).CompetorWay;
            switch (_CurrentType)
            {
                case "字符型": 
                    cb.ItemsSource = QueryValueCompetor.StringCompetors;
                    foreach (var item in cb.ItemsSource)
                    {
                        if ((item as Common.CompetorClass).Sign.Equals(sign))
                            cb.SelectedItem = item;

                    }
                    break;
                case "数字型":
                case "日期型":
                    cb.ItemsSource = QueryValueCompetor.DateIntCompetors;
                    foreach (var item in cb.ItemsSource)
                    {
                        if ((item as Common.CompetorClass).Sign.Equals(sign))
                            cb.SelectedItem = item;

                    }
                    break;
            }
         
       
        }
    }
}

